package socket

// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
	// Registered clients.
	Clients map[string]*Client

	// Inbound messages from the clients.
	Broadcast chan []byte

	// Register requests from the clients.
	Register chan map[string]*Client

	// Unregister requests from clients.
	Unregister chan map[string]*Client
}

func NewHub() *Hub {
	return &Hub{
		Broadcast:  make(chan []byte),
		Register:   make(chan map[string]*Client),
		Unregister: make(chan map[string]*Client),
		Clients:    make(map[string]*Client),
	}
}

func (h *Hub) Run() {
	for {
		select {
		case client := <-h.Register:
			for s, c := range client {
				h.Clients[s] = c
			}

		case client := <-h.Unregister:
			for s, c := range client {
				if _, ok := h.Clients[s]; ok {
					delete(h.Clients, s)
					close(c.Send)
				}
			}

			//case message := <-h.Broadcast:
			//	for client := range h.Clients {
			//		select {
			//		case client.Send <- message:
			//		default:
			//			close(client.Send)
			//			delete(h.Clients, client)
			//		}
			//	}
		}
	}
}
